﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Core.Common.CommandTrees;


namespace SistemaAdministracion.Models.PatternBase
{
    class BaseRepository<T> : IRepository<T> where T : class
    {
        private readonly IDbContext _context;
        private readonly DbSet<T> _set;

        public BaseRepository(IDbContext context)
        {
            this._context = context;
            this._set = _context.CreateDbSet<T>();
        }

        public IEnumerable<T> GetAll()
        {
            return _set.ToList();
        }

        public IEnumerable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return _set.Where(where);
        }

        public T Single(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return _set.Single(where);
        }

        public T First(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return _set.First(where);
        }

        public void Delete(T Entity)
        {
            _set.Remove(Entity);
            _context.ChangeObjectState(Entity, EntityState.Deleted);
        }

        public void Add(T Entity)
        {
            _set.Add(Entity);
            _context.ChangeObjectState(Entity, EntityState.Added);
        }

        public void Attach(T Entity)
        {
            _set.Attach(Entity);
            _context.ChangeObjectState(Entity, EntityState.Modified);
        }

        public T SingleOrDefault(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return _set.SingleOrDefault(where);
        }

        public T FistOrDefault(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return _set.FirstOrDefault(where);
        }

        public T SingleOrDefault()
        {
            return _set.SingleOrDefault();
        }

        public T FistOrDefault()
        {
            return _set.FirstOrDefault();
        }
        
    }

}
